import SwiftUI
import PhotosUI
import CoreLocation

// MARK: - 优化的图片缓存管理器
class ImageCache {
    static let shared = ImageCache()
    private var cache = NSCache<NSString, UIImage>()
    private var loadingTasks: [String: Task<Void, Never>] = [:]
    
    private init() {
        cache.countLimit = 200 // 增加缓存数量
        cache.totalCostLimit = 1024 * 1024 * 100 // 100MB
    }
    
    func get(forKey key: String) -> UIImage? {
        return cache.object(forKey: NSString(string: key))
    }
    
    func set(_ image: UIImage, forKey key: String) {
        cache.setObject(image, forKey: NSString(string: key))
    }
    
    func clearCache() {
        cache.removeAllObjects()
        print("🗑️ 图片缓存已清理")
    }
    
    func getMemoryUsage() -> Int {
        return Int(cache.totalCostLimit / 1024 / 1024)
    }
}

// MARK: - 优化的照片缩略图组件
struct OptimizedPhotoThumbnail: View {
    let photo: PhotoData
    let size: CGSize
    let cornerRadius: CGFloat
    let onTap: () -> Void
    
    @State private var thumbnail: UIImage?
    @State private var isLoading = false
    @State private var loadError = false
    
    var body: some View {
        Button(action: onTap) {
            Group {
                if let thumbnail = thumbnail {
                    Image(uiImage: thumbnail)
                        .resizable()
                        .aspectRatio(contentMode: .fill)
                        .frame(width: size.width, height: size.height)
                        .clipped()
                        .cornerRadius(cornerRadius)
                } else if isLoading {
                    // 加载状态
                    ProgressView()
                        .frame(width: size.width, height: size.height)
                        .background(Color(.systemGray6))
                        .cornerRadius(cornerRadius)
                } else if loadError {
                    // 错误状态
                    Image(systemName: "photo")
                        .font(.system(size: 20))
                        .foregroundColor(.gray)
                        .frame(width: size.width, height: size.height)
                        .background(Color(.systemGray6))
                        .cornerRadius(cornerRadius)
                } else {
                    // 占位符
                    Color(.systemGray6)
                        .frame(width: size.width, height: size.height)
                        .cornerRadius(cornerRadius)
                }
            }
        }
        .buttonStyle(PlainButtonStyle())
        .onAppear {
            loadThumbnail()
        }
    }
    
    private func loadThumbnail() {
        // 如果已经有缩略图，直接使用
        if let existingThumbnail = photo.thumbnail {
            thumbnail = existingThumbnail
            return
        }
        
        // 检查缓存
        let cacheKey = "\(photo.id)_\(Int(size.width))x\(Int(size.height))"
        if let cachedThumbnail = ImageCache.shared.get(forKey: cacheKey) {
            thumbnail = cachedThumbnail
            return
        }
        
        // 异步加载缩略图
        guard !isLoading else { return }
        isLoading = true
        
        Task {
            do {
                let thumbnail = try await loadThumbnailAsync()
                await MainActor.run {
                    self.thumbnail = thumbnail
                    self.isLoading = false
                    // 缓存缩略图
                    ImageCache.shared.set(thumbnail, forKey: cacheKey)
                }
            } catch {
                await MainActor.run {
                    self.loadError = true
                    self.isLoading = false
                    print("❌ 缩略图加载失败: \(photo.id), 错误: \(error.localizedDescription)")
                }
            }
        }
    }
    
    private func loadThumbnailAsync() async throws -> UIImage {
        return try await withCheckedThrowingContinuation { continuation in
            let options = PHImageRequestOptions()
            options.deliveryMode = .fastFormat
            options.isNetworkAccessAllowed = true
            options.isSynchronous = false
            
            PHImageManager.default().requestImage(
                for: photo.asset,
                targetSize: size,
                contentMode: .aspectFill,
                options: options
            ) { image, info in
                if let image = image {
                    continuation.resume(returning: image)
                } else {
                    let error = NSError(domain: "PhotoThumbnailError", code: -1, userInfo: [NSLocalizedDescriptionKey: "缩略图加载失败"])
                    continuation.resume(throwing: error)
                }
            }
        }
    }
}

// MARK: - Image扩展
extension Image {
    func asUIImage() -> UIImage? {
        let controller = UIHostingController(rootView: self)
        let view = controller.view
        
        let targetSize = controller.view.intrinsicContentSize
        view?.bounds = CGRect(origin: .zero, size: targetSize)
        view?.backgroundColor = .clear
        
        let renderer = UIGraphicsImageRenderer(size: targetSize)
        return renderer.image { _ in
            view?.drawHierarchy(in: controller.view.bounds, afterScreenUpdates: true)
        }
    }
}

// MARK: - 主视图
struct LocationAxisView: View {
    @EnvironmentObject var photoService: PhotoService
    @StateObject private var locationGroupService = LocationGroupService()
    @State private var expandedGroups: Set<String> = []
    @State private var expandedSubGroups: Set<String> = []
    @State private var showAllExpanded = false
    @State private var showMap = false
    @State private var showShareSheet: LocationGroup? = nil
    @State private var preloadedImages: Set<String> = []
    @State private var refreshTrigger = false // 🚀 新增：UI刷新触发器
    
    // 🎯 优化：静态变量用于减少重复日志
    #if DEBUG
    private static var lastGroupCount = 0
    #endif
    
    // 计算属性：使用新的LocationGroupService生成地点组
    private var locationGroups: [LocationGroup] {
        let _ = refreshTrigger
        let startTime = Date()
        
        let groups = locationGroupService.getLocationGroups(from: photoService.photos)
        
        let endTime = Date()
        let duration = endTime.timeIntervalSince(startTime)
        
        // 🎯 优化：减少重复日志，只在特定条件下打印
        #if DEBUG
        // 只在分组数量发生变化或耗时较长时打印
        if groups.count != Self.lastGroupCount || duration > 0.1 {
            print("🟢 [调试] locationGroups 计算属性被触发")
            print("🟢 [调试] LocationGroupService 返回 \(groups.count) 个分组")
            print("⏱️ 分组计算耗时: \(String(format: "%.3f", duration)) 秒")
            Self.lastGroupCount = groups.count
        }
        
        // 只在分组数量较少时打印详情
        if groups.count <= 10 && groups.count != Self.lastGroupCount {
            for group in groups {
                print("🟢 [分组] id:\(group.id) city:\(group.city) isParent:\(group.isParentNode) parentCity:\(group.parentCity ?? "nil") total:\(group.totalPhotos) detail:\(group.detailedLocation ?? "nil")")
            }
        }
        #endif
        
        return groups
    }
    
    var body: some View {
        NavigationView {
            ScrollView {
                LazyVStack(spacing: 20) {
                    // 顶部统计信息
                    if !photoService.photos.isEmpty {
                        StatisticsHeaderView(photoService: photoService, locationGroups: locationGroups)
                    }
                    // 地点组列表
                    ForEach(locationGroups.filter { $0.isParentNode }) { parentGroup in
                        locationGroupView(for: parentGroup)
                    }
                }
                .padding(.horizontal, 16)
                .padding(.top, 20)
            }
            // 🚀 正确位置：监听刷新通知，触发UI更新
            .onReceive(NotificationCenter.default.publisher(for: NSNotification.Name("RefreshLocationAxis"))) { _ in
                print("🟢 [调试] 收到RefreshLocationAxis通知，准备刷新UI")
                refreshTrigger.toggle()
                // 🚀 性能优化：减少调试日志，只在调试模式时打印
        #if DEBUG
        print("🟢 [调试] 刷新后locationGroups数量: \(locationGroups.count)")
        #endif
            }
            .navigationTitle("地点回忆")
            .navigationBarTitleDisplayMode(.large)
            .toolbar {
                toolbarContent
            }
        }
        .sheet(isPresented: $showMap) {
            Text("地图视图")
                .font(.title)
        }
        .sheet(item: $showShareSheet) { group in
            ShareSheet(items: [group.country + " - " + group.city])
        }
        .onAppear {
            // 监控内存使用
            monitorMemoryUsage()
        }
        .onDisappear {
            // 清理内存
            cleanupMemory()
        }
    }
    
    // MARK: - 子视图
    
    @ViewBuilder
    private func locationGroupView(for parentGroup: LocationGroup) -> some View {
        VStack(spacing: 0) {
            // 父节点（城市级别）
            LocationGroupCard(
                group: parentGroup,
                isExpanded: expandedGroups.contains(parentGroup.city),
                onToggle: {
                    if expandedGroups.contains(parentGroup.city) {
                        expandedGroups.remove(parentGroup.city)
                    } else {
                        expandedGroups.insert(parentGroup.city)
                    }
                },
                onLocationTap: { photo in }
            )
            .environmentObject(photoService)
            .onAppear {
                // 🚀 性能优化：减少调试日志，只在调试模式时打印
                #if DEBUG
                print("🟢 [调试] 父节点卡片渲染: \(parentGroup.city) [\(parentGroup.totalPhotos)张] isParent:\(parentGroup.isParentNode)")
                #endif
            }
            // 子节点列表
            if expandedGroups.contains(parentGroup.city) {
                childGroupsView(for: parentGroup)
            }
        }
        .onAppear {
            // print("✅ [地点轴] 父节点容器渲染完成: \(parentGroup.city)")
        }
    }
    
    @ViewBuilder
    private func childGroupsView(for parentGroup: LocationGroup) -> some View {
        let childGroups = locationGroups.filter { 
            !$0.isParentNode && $0.parentCity == parentGroup.city 
        }
        
        // 使用空的View来包装调试日志
        EmptyView()
            .onAppear {
                print("🟢 [调试] 渲染父节点: \(parentGroup.city) 子节点数: \(childGroups.count)")
                childGroups.forEach { child in
                    print("🟢 [子节点] id:\(child.id) city:\(child.city) parentCity:\(child.parentCity ?? "nil") detail:\(child.detailedLocation ?? "nil") total:\(child.totalPhotos)")
                }
        }
        
        ForEach(childGroups) { childGroup in
            LocationSubGroupCard(
                group: childGroup,
                isExpanded: expandedSubGroups.contains(childGroup.id),
                onToggle: {
                    if expandedSubGroups.contains(childGroup.id) {
                        expandedSubGroups.remove(childGroup.id)
                    } else {
                        expandedSubGroups.insert(childGroup.id)
                    }
                },
                onLocationTap: { photo in }
            )
            .environmentObject(photoService)
            .onAppear {
                print("🟢 [调试] 子节点卡片渲染: \(childGroup.detailedLocation ?? "nil") [\(childGroup.totalPhotos)张] parentCity:\(childGroup.parentCity ?? "nil")")
            }
        }
        .transition(.opacity.combined(with: .scale(scale: 0.95)))
        .onAppear {
            // print("✅ [地点轴] 子节点容器渲染完成: 父城市=\(parentGroup.city)，子节点数=\(childGroups.count)")
        }
    }
    
    private var toolbarContent: some ToolbarContent {
        ToolbarItem(placement: .navigationBarTrailing) {
            HStack(spacing: 16) {
                // 刷新按钮
                Button(action: {
                    locationGroupService.clearAllGroups()
                    refreshTrigger.toggle()
                }) {
                    Image(systemName: "arrow.clockwise")
                        .font(.title2)
                        .foregroundColor(.blue)
                }
                
                // 地图按钮
                Button(action: { showMap = true }) {
                    Image(systemName: "map")
                        .font(.title2)
                        .foregroundColor(.blue)
                }
                
                // 分享按钮
                Button(action: {
                    if let firstGroup = locationGroups.first {
                        showShareSheet = firstGroup
                    }
                }) {
                    Image(systemName: "square.and.arrow.up")
                        .font(.title2)
                        .foregroundColor(.blue)
                }
            }
        }
    }
    
    // MARK: - 刷新功能
    
    private func scanAndRefreshPhotos() async {
        print("🔄 开始扫描相册，检查新照片...")
        
        // 显示加载状态
        await MainActor.run {
            // 可以在这里添加加载指示器
        }
        
        // 清除所有缓存数据，强制重新加载所有照片
        photoService.clearAllCache()
        
        // 调用PhotoService的加载方法
        await photoService.loadAllPhotos()
        
        print("🔄 相册扫描完成")
    }
    
    // MARK: - 辅助方法
    
    private func getCountryFlag(for country: String) -> String {
        // 简单的国家到国旗映射
        let flagMap: [String: String] = [
            "中国": "🇨🇳",
            "日本": "🇯🇵",
            "韩国": "🇰🇷",
            "美国": "🇺🇸",
            "英国": "🇬🇧",
            "法国": "🇫🇷",
            "德国": "🇩🇪",
            "意大利": "🇮🇹",
            "西班牙": "🇪🇸",
            "加拿大": "🇨🇦",
            "澳大利亚": "🇦🇺"
        ]
        
        return flagMap[country] ?? "🏳️"
    }
    
    // MARK: - 内存管理
    
    private func monitorMemoryUsage() {
        let memoryUsage = getMemoryUsage()
        print("💾 当前内存使用: \(memoryUsage) MB")
        
        // 如果内存使用过高，清理缓存
        if memoryUsage > 200 {
            print("⚠️ 内存使用过高，清理图片缓存")
            ImageCache.shared.clearCache()
        }
    }
    
    private func cleanupMemory() {
        print("🧹 清理内存资源")
        ImageCache.shared.clearCache()
    }
    
    private func getMemoryUsage() -> Int {
        var info = mach_task_basic_info()
        var count = mach_msg_type_number_t(MemoryLayout<mach_task_basic_info>.size)/4
        
        let kerr: kern_return_t = withUnsafeMutablePointer(to: &info) {
            $0.withMemoryRebound(to: integer_t.self, capacity: 1) {
                task_info(mach_task_self_,
                         task_flavor_t(MACH_TASK_BASIC_INFO),
                         $0,
                         &count)
            }
        }
        
        if kerr == KERN_SUCCESS {
            return Int(info.resident_size / 1024 / 1024) // 转换为MB
        }
        return 0
    }
}

// MARK: - 地点子组卡片
struct LocationSubGroupCard: View {
    let group: LocationGroup
    let isExpanded: Bool
    let onToggle: () -> Void
    let onLocationTap: (PhotoData) -> Void
    @EnvironmentObject var photoService: PhotoService
    
    var body: some View {
        // let _ = print("🔍 [子组卡片] 开始渲染: \(group.detailedLocation ?? "未知") - 照片数: \(group.totalPhotos)")
        VStack(spacing: 0) {
            // 子节点bar - 使用Button包装整个区域
            Button(action: {
                onToggle()
            }) {
                HStack {
                    // 缩进指示
                    Rectangle()
                        .fill(Color.gray.opacity(0.3))
                        .frame(width: 4, height: 40)
                        .cornerRadius(2)
                    
                    // 地点信息
                    VStack(alignment: .leading, spacing: 2) {
                        Text(group.detailedLocation ?? group.city)
                            .font(.subheadline)
                            .foregroundColor(.primary)
                        
                        Text(getDateRangeText(for: group.photos))
                            .font(.caption)
                            .foregroundColor(.secondary)
                    }
                    
                    Spacer()
                    
                    // 照片数量
                    Text("\(getRealTimePhotoCount(for: group))张")
                        .font(.caption)
                        .foregroundColor(.blue)
                        .padding(.horizontal, 8)
                        .padding(.vertical, 4)
                        .background(Color.blue.opacity(0.1))
                        .cornerRadius(6)
                    
                    // 展开/收缩图标
                    Image(systemName: isExpanded ? "chevron.up" : "chevron.down")
                        .font(.caption)
                        .foregroundColor(.secondary)
                        .rotationEffect(.degrees(isExpanded ? 0 : 0))
                        .animation(.easeInOut(duration: 0.3), value: isExpanded)
                }
                .padding(.horizontal, 16)
                .padding(.vertical, 8)
                .background(
                    RoundedRectangle(cornerRadius: 8)
                        .fill(Color(.systemGray6))
                        .overlay(
                            RoundedRectangle(cornerRadius: 8)
                                .stroke(Color.blue.opacity(0.3), lineWidth: 1)
                        )
                )
            }
            .buttonStyle(PlainButtonStyle())
            .scaleEffect(isExpanded ? 1.02 : 1.0)
            .animation(.easeInOut(duration: 0.2), value: isExpanded)
            
            // 照片网格（仅在展开时显示）
            if isExpanded {
                LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 4), count: 4), spacing: 4) {
                    ForEach(group.photos.prefix(12)) { photo in
                        OptimizedPhotoThumbnail(
                            photo: photo,
                            size: CGSize(width: 60, height: 60),
                            cornerRadius: 6
                        ) {
                            onLocationTap(photo)
                        }
                    }
                }
                .padding(.top, 8)
                .transition(.opacity.combined(with: .scale(scale: 0.95)))
            }
        }
        .padding(.leading, 20) // 子节点缩进
        .animation(.easeInOut(duration: 0.3), value: isExpanded)
        .onAppear {
            // print("✅ [子组卡片] 渲染成功: \(group.detailedLocation ?? "未知") - 照片数: \(group.totalPhotos)")
        }
        .onDisappear {
            // print("🔄 [子组卡片] 消失: \(group.detailedLocation ?? "未知")")
        }
    }
    
    private func getDateRangeText(for photos: [PhotoData]) -> String {
        guard !photos.isEmpty else { return "未知日期" }
        
        let sortedPhotos = photos.sorted { $0.creationDate < $1.creationDate }
        let firstDate = sortedPhotos.first!.creationDate
        let lastDate = sortedPhotos.last!.creationDate
        
        let formatter = DateFormatter()
        formatter.dateFormat = "MM月dd日"
        
        let startDate = formatter.string(from: firstDate)
        let endDate = formatter.string(from: lastDate)
        
        if Calendar.current.isDate(firstDate, inSameDayAs: lastDate) {
            return startDate
        } else {
            return "\(startDate) - \(endDate)"
        }
    }
    
    private func calculateDateRange(from photos: [PhotoData]) -> String {
        guard !photos.isEmpty else { return "未知日期" }
        
        let sortedPhotos = photos.sorted { $0.creationDate < $1.creationDate }
        let firstDate = sortedPhotos.first!.creationDate
        let lastDate = sortedPhotos.last!.creationDate
        
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy年MM月dd日"
        
        let startDate = formatter.string(from: firstDate)
        let endDate = formatter.string(from: lastDate)
        
        if Calendar.current.isDate(firstDate, inSameDayAs: lastDate) {
            return startDate
        } else {
            return "\(startDate) - \(endDate)"
        }
    }
    
    private func formatDate(_ date: Date) -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        return formatter.string(from: date)
    }
    
    // 🚀 新增：获取实时照片数量，支持未知地点的实时更新
    private func getRealTimePhotoCount(for group: LocationGroup) -> Int {
        // 如果是未知城市且正在解析中，使用实时更新的数量
        if (group.city == "未知城市" || group.country == "未知国家") && photoService.isGeocodingInProgress {
            return photoService.unknownPhotosCount
        }
        // 否则使用原始数量
        return group.totalPhotos
    }
}

// MARK: - 统计头部视图
struct StatisticsHeaderView: View {
    @ObservedObject var photoService: PhotoService
    let locationGroups: [LocationGroup]
    
    private var dateRangeText: String? {
        let statistics = PhotoStatistics(photos: photoService.photos)
        guard let dateRange = statistics.dateRange else { return nil }
        
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy年MM月"
        let startDate = formatter.string(from: dateRange.lowerBound)
        let endDate = formatter.string(from: dateRange.upperBound)
        
        return startDate == endDate ? startDate : "\(startDate) - \(endDate)"
    }
    
    var body: some View {
        VStack(spacing: 12) {
            HStack {
                VStack(alignment: .leading, spacing: 4) {
                    Text("\(photoService.photos.filter { $0.location != nil }.count)")
                        .font(.title2)
                        .fontWeight(.bold)
                        .foregroundColor(.orange)
                    
                    Text("有地理信息照片")
                        .font(.caption)
                        .foregroundColor(.secondary)
                }
                
                Spacer()
                
                VStack(alignment: .center, spacing: 4) {
                    Text("\(photoService.photos.filter { $0.location != nil }.count)")
                        .font(.title2)
                        .fontWeight(.bold)
                        .foregroundColor(.blue)
                    
                    Text("有地理信息照片")
                        .font(.caption)
                        .foregroundColor(.secondary)
                }
                
                Spacer()
                
                VStack(alignment: .trailing, spacing: 4) {
                    Text("\(locationGroups.filter { $0.isParentNode }.count)")
                        .font(.title2)
                        .fontWeight(.bold)
                        .foregroundColor(.green)
                    
                    Text("个地点")
                        .font(.caption)
                        .foregroundColor(.secondary)
                }
            }
            
            if let dateRangeText = dateRangeText {
                Text("时间跨度: \(dateRangeText)")
                    .font(.caption)
                    .foregroundColor(.secondary)
            }
        }
        .padding()
        .background(Color(.systemGray6))
        .cornerRadius(12)
    }
}

// MARK: - 地点组卡片
struct LocationGroupCard: View {
    let group: LocationGroup
    let isExpanded: Bool
    let onToggle: () -> Void
    let onLocationTap: (PhotoData) -> Void
    @EnvironmentObject var photoService: PhotoService
    
    @State private var showAnalysisAlert = false
    
    var body: some View {
        // let _ = print("🔍 [父组卡片] 开始渲染: \(group.city) - 照片数: \(group.totalPhotos), 国家: \(group.country)")
        VStack(spacing: 0) {
            // 父节点bar
            Button(action: onToggle) {
                HStack {
                    // 国旗和地点信息
                    HStack(spacing: 12) {
                        // 国旗按钮 - 如果是待识别照片，添加点击事件
                        if isUnknownLocation() {
                            Button(action: {
                                showAnalysisAlert = true
                            }) {
                                Text(getCountryFlag(for: group.country))
                                    .font(.title2)
                                    .foregroundColor(.blue) // 添加蓝色提示
                            }
                            .buttonStyle(PlainButtonStyle())
                        } else {
                            Text(getCountryFlag(for: group.country))
                                .font(.title2)
                        }
                        
                        VStack(alignment: .leading, spacing: 2) {
                            Text(getDisplayName(for: group))
                                .font(.headline)
                                .foregroundColor(.primary)
                            
                            Text("\(getRealTimePhotoCount(for: group))张照片")
                                .font(.subheadline)
                                .foregroundColor(.secondary)
                            
                            Text(getDateRangeText(for: group.photos))
                                .font(.caption)
                                .foregroundColor(.secondary)
                        }
                    }
                    
                    Spacer()
                    
                    // 展开/折叠图标
                    Image(systemName: isExpanded ? "chevron.up" : "chevron.down")
                        .font(.title3)
                        .foregroundColor(.secondary)
                        .rotationEffect(.degrees(isExpanded ? 0 : 0))
                        .animation(.easeInOut(duration: 0.3), value: isExpanded)
                }
                .padding(.horizontal, 16)
                .padding(.vertical, 12)
                .background(
                    // 水印背景
                    ZStack {
                        Color(.systemBackground)
                        
                        if let image = group.coverPhoto {
                            Image(uiImage: image)
                                .resizable()
                                .aspectRatio(contentMode: .fill)
                                .opacity(0.1)
                        }
                    }
                )
                .cornerRadius(12)
            }
            .buttonStyle(PlainButtonStyle())
        }
        .animation(.easeInOut(duration: 0.3), value: isExpanded)
        .onAppear {
            // print("✅ [父组卡片] 渲染成功: \(group.city) - 照片数: \(group.totalPhotos)")
        }
        .onDisappear {
            // print("🔄 [父组卡片] 消失: \(group.city)")
        }
        .alert("开始地址解析", isPresented: $showAnalysisAlert) {
            Button("开始解析") {
                startOptimizedBatchAnalysis()
            }
            Button("取消", role: .cancel) {
                // 用户选择不解析
            }
        } message: {
            Text("是否要开始优化版批量解析？\n\n将解析1000张照片，预计耗时5-20秒。")
        }
    }
    
    // 检查是否为待识别照片
    private func isUnknownLocation() -> Bool {
        return group.country == "待识别照片" || group.country == "无法识别未知照片"
    }
    
    // 开始地点分析
    private func startLocationAnalysis() {
        print("🔍 用户选择解析地址: \(group.city), 照片数: \(group.totalPhotos)")
        
        // 通知PhotoService开始对指定分组的照片进行地理编码
        NotificationCenter.default.post(
            name: NSNotification.Name("StartLocationAnalysis"),
            object: nil,
            userInfo: [
                "group": group,
                "photos": group.photos,
                "photoCount": group.totalPhotos
            ]
        )
    }
    
    // 🚀 新增：开始优化版批量解析
    private func startOptimizedBatchAnalysis() {
        print("🚀 === 开始优化版批量解析 ===")
        print("🚀 用户选择优化版批量解析: \(group.city), 固定解析1000张照片")
        
        // 解析前：统计当前待识别照片数量
        let unknownPhotosBefore = photoService.photos.filter { photo in
            guard let location = photo.location else { return true }
            let hasAddress = location.address != nil && location.address != "未知" && location.address != "未知地点"
            let hasCity = location.city != nil && location.city != "未知" && location.city != "未知城市"
            let hasCountry = location.country != nil && location.country != "未知" && location.country != "未知国家"
            return !hasAddress || !hasCity || !hasCountry
        }
        
        print("🚀 [解析前] 待识别照片数量: \(unknownPhotosBefore.count)")
        
        // 直接调用优化版批量解析，固定解析1000张照片
        Task {
            await photoService.batchParseUnknownPhotosOptimized(count: 1000)
            
            // 解析后：统计当前待识别照片数量
            await MainActor.run {
                let unknownPhotosAfter = photoService.photos.filter { photo in
                    guard let location = photo.location else { return true }
                    let hasAddress = location.address != nil && location.address != "未知" && location.address != "未知地点"
                    let hasCity = location.city != nil && location.city != "未知" && location.city != "未知城市"
                    let hasCountry = location.country != nil && location.country != "未知" && location.country != "未知国家"
                    return !hasAddress || !hasCity || !hasCountry
                }
                
                print("🚀 [解析后] 待识别照片数量: \(unknownPhotosAfter.count)")
                print("🚀 [变化] 待识别照片减少: \(unknownPhotosBefore.count - unknownPhotosAfter.count)")
                print("🚀 === 优化版批量解析完成 ===")
            }
        }
    }
    
    private func getCountryFlag(for country: String) -> String {
        // 简单的国家到国旗映射
        let flagMap: [String: String] = [
            "中国": "🇨🇳",
            "日本": "🇯🇵",
            "韩国": "🇰🇷",
            "美国": "🇺🇸",
            "英国": "🇬🇧",
            "法国": "🇫🇷",
            "德国": "🇩🇪",
            "意大利": "🇮🇹",
            "西班牙": "🇪🇸",
            "加拿大": "🇨🇦",
            "澳大利亚": "🇦🇺"
        ]
        
        return flagMap[country] ?? "🏳️"
    }
    
    private func getDisplayName(for group: LocationGroup) -> String {
        if !group.country.isEmpty && group.country != "未知国家" {
            return "\(group.country) \(group.city)"
        } else {
            return group.city
        }
    }
    
    private func getDateRangeText(for photos: [PhotoData]) -> String {
        guard !photos.isEmpty else { return "无日期信息" }
        
        let dates = photos.map { $0.creationDate }
        guard let minDate = dates.min(),
              let maxDate = dates.max() else {
            return "无日期信息"
        }
        
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM"
        
        let startDate = formatter.string(from: minDate)
        let endDate = formatter.string(from: maxDate)
        
        if startDate == endDate {
            return startDate
        } else {
            return "\(startDate) - \(endDate)"
        }
    }
    
    // 🚀 新增：获取实时照片数量，支持未知地点的实时更新
    private func getRealTimePhotoCount(for group: LocationGroup) -> Int {
        // 如果是未知城市且正在解析中，使用实时更新的数量
        if (group.city == "未知城市" || group.country == "未知国家") && photoService.isGeocodingInProgress {
            return photoService.unknownPhotosCount
        }
        // 否则使用原始数量
        return group.totalPhotos
    }
}

// MARK: - 照片项目行
struct PhotoItemRow: View {
    let photo: PhotoData
    let onTap: () -> Void
    @EnvironmentObject var photoService: PhotoService
    
    var body: some View {
        Button(action: onTap) {
            HStack(spacing: 12) {
                // 缩略图
                if let thumbnail = photo.thumbnail {
                    Image(uiImage: thumbnail)
                        .resizable()
                        .aspectRatio(contentMode: .fill)
                        .frame(width: 40, height: 40)
                        .clipped()
                        .cornerRadius(8)
                } else {
                    Color(.systemGray5)
                        .frame(width: 40, height: 40)
                        .cornerRadius(8)
                }
                
                VStack(alignment: .leading, spacing: 2) {
                    Text(photo.location?.displayName ?? "未知地点")
                        .font(.subheadline)
                        .fontWeight(.medium)
                        .foregroundColor(.primary)
                    
                    Text(formatDate(photo.creationDate))
                        .font(.caption)
                        .foregroundColor(.secondary)
                }
                
                Spacer()
                
                // 显示照片数量（这里每行都是1张照片）
                Text("1")
                    .font(.caption)
                    .foregroundColor(.blue)
                    .padding(.horizontal, 8)
                    .padding(.vertical, 4)
                    .background(Color.blue.opacity(0.1))
                    .cornerRadius(6)
            }
            .padding(.horizontal, 16)
            .padding(.vertical, 8)
            .background(Color(.systemGray6))
            .cornerRadius(8)
        }
        .buttonStyle(PlainButtonStyle())
    }
    
    private func formatDate(_ date: Date) -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        return formatter.string(from: date)
    }
}

// MARK: - 分享视图
struct ShareSheet: UIViewControllerRepresentable {
    let items: [Any]
    
    func makeUIViewController(context: Context) -> UIActivityViewController {
        let controller = UIActivityViewController(activityItems: items, applicationActivities: nil)
        return controller
    }
    
    func updateUIViewController(_ uiViewController: UIActivityViewController, context: Context) {}
}

#Preview {
    LocationAxisView()
        .environmentObject(PhotoService())
} 